<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>hash</title>
  </head>
  <body>
    <div></div>
    <button class="random">随机</button>
    <button class="forward">前进</button>
    <button class="back">后退</button>
    <button class="reload">刷新</button>
    <script>
      //浏览器地址前进后退是不会刷新页面的
      const div = document.querySelector('div')
      const randomHash = ['/forward', '/back', '/ggg', '/yyy']
      window.addEventListener('hashchange', (e) => {
        // if (e.oldURL === e.newURL) {
        //   return
        // }
        setHtml()
      })
      document.querySelector('.random').addEventListener('click', () => {
        location.hash = randomHash[Math.floor(Math.random() * randomHash.length)]
      })
      document.querySelector('.forward').addEventListener('click', () => {
        // history.forward()
        location.hash = '/forward'
      })

      document.querySelector('.back').addEventListener('click', () => {
        // history.back()
        location.hash = '/back'
      })
      document.querySelector('.reload').addEventListener('click', () => {
        // 刷新之后直接变成了第一个页面了,初始页面
        location.reload()
      })

      /*
        调用pushState和replaceState 不会调用popstate事件,且不会触发浏览器的加载机制

      */
      /* 
      1. hash设置的新值必须和之前的不同才会被添加进历史记录栈
     
     */

      const routes = [
        {
          name: 'forward',
          path: '/forward',
          html: 'forward'
        },
        {
          name: 'ggg',
          path: '/ggg',
          html: 'ggg'
        },
        {
          name: 'yyy',
          path: '/yyy',
          html: 'yyy'
        },
        {
          name: 'back',
          path: '/back',
          html: 'back'
        }
      ]
      // location.hash = 1
      location.hash = randomHash[Math.floor(Math.random() * randomHash.length)]
      setHtml()
      function getHashPath() {
        return window.location.hash.slice(1)
      }
      function getCurrentPage() {
        return routes.find((item) => item.path == getHashPath())
      }
      function getHtml() {
        return getCurrentPage()?.html
      }
      function setHtml() {
        div.innerHTML = getHtml()
      }
    </script>
  </body>
</html>
